package com.rivues.module.manage.web.handler.help;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.eigenbase.xom.MetaDef.Model;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.rivues.core.RivuDataContext;
import com.rivues.module.manage.web.service.AccountService;
import com.rivues.module.platform.web.bean.HelpDetail;
import com.rivues.module.platform.web.bean.HelpGroup;
import com.rivues.module.platform.web.exception.BusinessException;
import com.rivues.module.platform.web.handler.Handler;
import com.rivues.module.platform.web.handler.RequestData;
import com.rivues.module.platform.web.handler.ResponseData;
import com.rivues.module.platform.web.interceptor.LogIntercreptorHandler;
import com.rivues.module.platform.web.model.Organ;
import com.rivues.module.platform.web.model.SearchResultTemplet;
import com.rivues.module.platform.web.model.TypeCategory;
import com.rivues.module.platform.web.model.User;
import com.rivues.module.platform.web.model.UserOrgan;
import com.rivues.module.platform.web.model.UserRole;
import com.rivues.module.report.web.model.PublishedReport;
import com.rivues.util.RivuTools;
import com.rivues.util.exception.ReportException;
import com.rivues.util.iface.authz.UserAuthzFactory;
import com.rivues.util.iface.report.ReportFactory;
import com.rivues.util.local.LocalTools;
import com.rivues.util.service.cache.CacheHelper;
  
@Controller  
@RequestMapping("/{orgi}/manage/help")  
public class HelpController extends Handler{
	private final Logger logger = LoggerFactory.getLogger(HelpController.class);
    @RequestMapping(value="/index" , name="index" , type="manage",subtype="help")
    public ModelAndView index(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data) throws Exception{ 
    	ModelAndView modelView = request(super.createManageTempletResponse("/pages/manage/help/index") , orgi) ;
    	SolrQuery params = new SolrQuery();
        params.set("q", "clazz:"+HelpGroup.class.getName());
        params.set("start", 0);
        params.set("rows", Integer.MAX_VALUE);
        params.set("sort", "sort asc");
        QueryResponse response = RivuDataContext.getSolrService().query(params);
        params.set("q", "clazz:"+HelpDetail.class.getName());
        QueryResponse response2 = RivuDataContext.getSolrService().query(params);
        modelView.addObject("groups", response.getResults());
        modelView.addObject("helps", response2.getResults());
    	return modelView;
    }
    @RequestMapping(value="/list/{groupid}" , name="list" , type="manage",subtype="help")
    public ModelAndView list(HttpServletRequest request , @PathVariable String orgi , @PathVariable String groupid) throws Exception{ 
    	ModelAndView modelView = request(super.createManageTempletResponse("/pages/manage/help/index") , orgi) ;
    	SolrQuery params = new SolrQuery();
        params.set("q", "clazz:"+HelpGroup.class.getName());
        params.set("start", 0);
        params.set("rows", Integer.MAX_VALUE);
        params.set("sort", "sort asc");
        QueryResponse response = RivuDataContext.getSolrService().query(params);
        modelView.addObject("groups", response.getResults());
        modelView.addObject("groupid", groupid);
        params.set("q", "clazz:"+HelpDetail.class.getName()+" AND groupid:"+groupid);
        QueryResponse response2 = RivuDataContext.getSolrService().query(params);
        modelView.addObject("helps", response2.getResults());
    	return modelView;
    }
    
    /**
	 * 
	 * @param request
	 * @param orgi
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/showhelp/{mantype}/index", name = "showhelp", type = "manage", subtype = "system")
	public ModelAndView showhelp(HttpServletRequest request,@PathVariable String orgi,@PathVariable String mantype)
			throws Exception {
		ModelAndView view = request(new ResponseData("/pages/manage/help/showhelp"),orgi);
		SolrQuery params = new SolrQuery();
        params.set("q", "clazz:"+HelpGroup.class.getName()+" AND code:"+mantype);
        params.set("start", 0);
        params.set("rows", Integer.MAX_VALUE);
        params.set("sort", "sort asc");
        QueryResponse response = RivuDataContext.getSolrService().query(params);
        SolrDocumentList list = response.getResults();
        view.addObject("groups", response.getResults());
        SolrDocumentList helps = new SolrDocumentList();
        for (SolrDocument solrDocument : list) {
        	params.set("q", "clazz:"+HelpDetail.class.getName()+" AND groupid:"+solrDocument.getFieldValue("id"));
            QueryResponse response2 = RivuDataContext.getSolrService().query(params);
            helps.addAll(0, response2.getResults());
		}
        view.addObject("helps", helps);
		return view;
	}
	
	@RequestMapping(value = "/showhelp/{helpid}", name = "helpdetail", type = "manage", subtype = "system")
	public ModelAndView helpdetail(HttpServletRequest request,@PathVariable String orgi,@PathVariable String helpid)
			throws Exception {
		ModelAndView view = request(new ResponseData("/pages/manage/help/helpdetail"),orgi);
		SolrQuery params = new SolrQuery();
        params.set("q", "clazz:"+HelpDetail.class.getName()+" AND id:"+helpid);
        params.set("start", 0);
        params.set("rows", Integer.MAX_VALUE);
        params.set("sort", "sort asc");
        QueryResponse response = RivuDataContext.getSolrService().query(params);
        if(response.getResults().size()>0){
        	view.addObject("help", response.getResults().get(0));
        }
		return view;
	}
    
    @RequestMapping(value="/{groupid}/helpadd" , name="helpadd" , type="manage",subtype="help")
    public ModelAndView helpadd(HttpServletRequest request , @PathVariable String orgi , @PathVariable String groupid) throws Exception{ 
    	ModelAndView modelView = request(new ResponseData("/pages/manage/help/helpedit") , orgi) ;
    	SolrQuery params = new SolrQuery();
    	params.set("q", "clazz:"+HelpGroup.class.getName()+" AND id:"+groupid);
        params.set("start", 0);
        params.set("rows", 1);
        params.set("sort", "sort asc");
        QueryResponse response = RivuDataContext.getSolrService().query(params);
        SolrDocumentList list = response.getResults();
        if(list.size()>0){
        	modelView.addObject("parent",list.get(0));
        }
        
    	return modelView;
    }
    
    @RequestMapping(value="/{groupid}/groupadd" , name="groupadd" , type="manage",subtype="help")
    public ModelAndView groupadd(HttpServletRequest request , @PathVariable String orgi , @PathVariable String groupid) throws Exception{ 
    	ModelAndView modelView = request(new ResponseData("/pages/manage/help/groupedit") , orgi) ;
    	SolrQuery params = new SolrQuery();
    	params.set("q", "clazz:"+HelpGroup.class.getName()+" AND id:"+groupid);
        params.set("start", 0);
        params.set("rows", 1);
        params.set("sort", "sort asc");
        QueryResponse response = RivuDataContext.getSolrService().query(params);
        SolrDocumentList list = response.getResults();
        if(list.size()>0){
        	modelView.addObject("parent",list.get(0));
        }
        
    	return modelView;
    }
    
    @RequestMapping(value="/{groupid}/groupedit" , name="groupedit" , type="manage",subtype="help")
    public ModelAndView groupedit(HttpServletRequest request , @PathVariable String orgi , @PathVariable String groupid) throws Exception{ 
    	ModelAndView modelView = request(new ResponseData("/pages/manage/help/groupedit") , orgi) ;
    	SolrQuery params = new SolrQuery();
    	params.set("q", "clazz:"+HelpGroup.class.getName()+" AND id:"+groupid);
        params.set("start", 0);
        params.set("rows", 1);
        params.set("sort", "sort asc");
        QueryResponse response = RivuDataContext.getSolrService().query(params);
        SolrDocumentList list = response.getResults();
        if(list.size()>0){
        	SolrDocument group = list.get(0);
        	modelView.addObject("group", group);
        	if(group.get("parentid")!=null&&!"0".equals(group.get("parentid").toString())){
        		params = new SolrQuery();
            	params.set("q", "clazz:"+HelpGroup.class.getName()+" AND id:"+group.get("parentid").toString());
                params.set("start", 0);
                params.set("rows", 1);
                params.set("sort", "sort asc");
                response = RivuDataContext.getSolrService().query(params);
                list = response.getResults();
                if(list.size()>0){
                	modelView.addObject("parent",list.get(0));
                }
        	}
        	
        }
        
    	return modelView;
    }
    
    @RequestMapping(value="/{groupid}/{helpid}/helpedit" , name="helpedit" , type="manage",subtype="help")
    public ModelAndView helpedit(HttpServletRequest request , @PathVariable String orgi , @PathVariable String groupid, @PathVariable String helpid) throws Exception{ 
    	ModelAndView modelView = request(new ResponseData("/pages/manage/help/helpedit") , orgi) ;
    	SolrQuery params = new SolrQuery();
    	params.set("q", "clazz:"+HelpDetail.class.getName()+" AND id:"+helpid);
        params.set("start", 0);
        params.set("rows", 1);
        params.set("sort", "sort asc");
        QueryResponse response = RivuDataContext.getSolrService().query(params);
        SolrDocumentList list = response.getResults();
        SolrDocument helpdetail = null;
        if(list.size()>0){
        	helpdetail = list.get(0);
        }
        modelView.addObject("helpdetail",helpdetail);
    	params.set("q", "clazz:"+HelpGroup.class.getName()+" AND id:"+helpdetail.getFieldValue("groupid"));
       
        response = RivuDataContext.getSolrService().query(params);
        list = response.getResults();
        if(list.size()>0){
        	modelView.addObject("parent",list.get(0));
        }
        
    	return modelView;
    }
    
    @RequestMapping(value="/groupaddo" , name="groupaddo" , type="manage",subtype="help")
    public ModelAndView groupaddo(HttpServletRequest request , @PathVariable String orgi ,@Valid HelpGroup group) throws Exception{
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/help/list/").append(group.getParentid()).append(".html").toString()) ;
    	ModelAndView modelView = request(responseData , orgi) ;
    	group.setId(String.valueOf(System.currentTimeMillis()));
    	group.setCreater(super.getUser(request).getId());
    	group.setCreatetime(new Date());
    	group.setUpdatetime(new Date());
    	group.setClazz(group.getClazz());
    	RivuDataContext.getSolrService().addBean(group);
    	RivuDataContext.getSolrService().commit();
    	return modelView;
    }
    
    @RequestMapping(value="/helpaddo" , name="helpaddo" , type="manage",subtype="help")
    public ModelAndView helpaddo(HttpServletRequest request , @PathVariable String orgi ,@Valid HelpDetail help) throws Exception{
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/help/list/").append(help.getGroupid()).append(".html").toString()) ;
    	ModelAndView modelView = request(responseData , orgi) ;
    	help.setCreater(super.getUser(request).getId());
    	help.setCreatetime(new Date());
    	help.setId(String.valueOf(System.currentTimeMillis()));
    	help.setUpdatetime(new Date());
    	help.setClazz(help.getClazz());
    	RivuDataContext.getSolrService().addBean(help);
    	RivuDataContext.getSolrService().commit();
    	return modelView;
    }
    
    @RequestMapping(value="/{groupid}/groupeditdo" , name="groupeditdo" , type="manage",subtype="help")
    public ModelAndView groupeditdo(HttpServletRequest request , @PathVariable String orgi ,@PathVariable String groupid,@Valid HelpGroup group) throws Exception{
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/help/list/").append(groupid).append(".html").toString()) ;
    	ModelAndView modelView = request(responseData , orgi) ;
    	SolrQuery params = new SolrQuery();
    	params.set("q", "clazz:"+HelpGroup.class.getName()+" AND id:"+groupid);
        params.set("start", 0);
        params.set("rows", 1);
        params.set("sort", "sort asc");
        QueryResponse response = RivuDataContext.getSolrService().query(params);
        SolrDocumentList list = response.getResults();
        if(list.size()>0){
        	SolrDocument solrgroup = list.get(0);
        	group.setId(groupid);
        	group.setClazz(solrgroup.get("clazz").toString());
        	group.setCreater(solrgroup.get("creater").toString());
        	group.setCreatetime((Date)solrgroup.get("createtime"));
        	group.setUpdatetime(new Date());
        	RivuDataContext.getSolrService().addBean(group);
        	RivuDataContext.getSolrService().commit();
        }
    	return modelView;
    }
    
    
    @RequestMapping(value="/{groupid}/{helpid}/helpedito" , name="helpedito" , type="manage",subtype="help")
    public ModelAndView helpedito(HttpServletRequest request , @PathVariable String orgi ,@PathVariable String groupid,@PathVariable String helpid,@Valid HelpDetail help) throws Exception{
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/help/list/").append(groupid).append(".html").toString()) ;
    	ModelAndView modelView = request(responseData , orgi) ;
    	SolrQuery params = new SolrQuery();
    	params.set("q", "clazz:"+HelpDetail.class.getName()+" AND id:"+helpid);
        params.set("start", 0);
        params.set("rows", 1);
        params.set("sort", "sort asc");
        QueryResponse response = RivuDataContext.getSolrService().query(params);
        SolrDocumentList list = response.getResults();
        if(list.size()>0){
        	SolrDocument solrgroup = list.get(0);
        	help.setId(helpid);
        	help.setClazz(solrgroup.get("clazz").toString());
        	help.setGroupid(solrgroup.get("groupid").toString());
        	help.setCreater(solrgroup.get("creater").toString());
        	help.setCreatetime((Date)solrgroup.get("createtime"));
        	help.setUpdatetime(new Date());
        	RivuDataContext.getSolrService().addBean(help);
        	RivuDataContext.getSolrService().commit();
        }
    	return modelView;
    }
    
    @RequestMapping(value="/{groupid}/groupdelo" , name="groupdelo" , type="manage",subtype="help")
    public ModelAndView groupdelo(HttpServletRequest request , @PathVariable String orgi ,@PathVariable String groupid) throws Exception{
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/help/list/").append(groupid).append(".html").toString()) ;
    	
    	SolrQuery params = new SolrQuery();
    	params.set("q", "clazz:"+HelpGroup.class.getName()+" AND id:"+groupid);
        params.set("start", 0);
        params.set("rows", 1);
        params.set("sort", "sort asc");
        QueryResponse response = RivuDataContext.getSolrService().query(params);
        SolrDocumentList list = response.getResults();
        if(list.size()>0){
        	SolrDocument solrgroup = list.get(0);
        	responseData.setPage(new StringBuffer().append("redirect:/{orgi}/manage/help/list/").append(solrgroup.get("parentid").toString()).append(".html").toString());
        	RivuDataContext.getSolrService().deleteById(groupid);
        	RivuDataContext.getSolrService().commit();
        }
        ModelAndView modelView = request(responseData , orgi) ;
    	return modelView;
    }
    
    @RequestMapping(value="/{groupid}/{helpid}/helpdelo" , name="helpdelo" , type="manage",subtype="help")
    public ModelAndView helpdelo(HttpServletRequest request , @PathVariable String orgi ,@PathVariable String groupid,@PathVariable String helpid) throws Exception{
    	ResponseData responseData = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/help/list/").append(groupid).append(".html").toString()) ;
    	
    	SolrQuery params = new SolrQuery();
    	params.set("q", "clazz:"+HelpDetail.class.getName()+" AND id:"+helpid);
        params.set("start", 0);
        params.set("rows", 1);
        params.set("sort", "sort asc");
        QueryResponse response = RivuDataContext.getSolrService().query(params);
        SolrDocumentList list = response.getResults();
        if(list.size()>0){
        	SolrDocument help = list.get(0);
        	RivuDataContext.getSolrService().deleteById(helpid);
        	RivuDataContext.getSolrService().commit();
        }
        ModelAndView modelView = request(responseData , orgi) ;
    	return modelView;
    }
    
    
} 